﻿using BackgroundWeb.Models;
using BackgroundWeb.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace BackgroundWeb.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly BackgroundWorkerQueue _backgroundWorkQueue;

        public HomeController(ILogger<HomeController> logger,BackgroundWorkerQueue backgroundWorkerQueue)
        {
            _logger = logger;
            _backgroundWorkQueue = backgroundWorkerQueue;
        }

        public IActionResult Index()
        {
            CallSlowApi();
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        private void CallSlowApi()
        {
            _logger.LogInformation($"Starting at {DateTime.UtcNow.TimeOfDay}");
            _backgroundWorkQueue.QueueBackgroundWorkItem(async token =>
            {
                await Task.Delay(10000);
                _logger.LogInformation($"Done at {DateTime.UtcNow.TimeOfDay}");
            });
        }
    }
}
